from flask import Blueprint, render_template, session, url_for, request
from py.Services.AccountService import *
from py.Services.LendService import LendService
from py.commonResponse.CommonResponse import *
from py.commonResponse.Dict import Dict

bp_user = Blueprint('user', __name__, url_prefix="/users")  # 蓝图使用方法，参数里给定文件名，还可以给定url前缀


#  用户登录  通过name与密码查询用户
@bp_user.route('/login', methods=['POST'])
def login():
    name = request.form['name']
    password = request.form['password']
    type = request.form['type']

    account = AccountService.Account_Query_ByPassword(name, password)

    if account is None:
        return createForErrorWM('账号或密码错误')
    elif account.authority != int(type):
        return createForErrorWM('登录身份错误')
    else:
        session['account'] = dict(account)
        return createForSuccessWMD('登陆成功', dict(account))


#  用户登出
@bp_user.route('logOut', methods=['GET'])
def logOut():
    session.pop('account', None)
    return createForErrorWM('用户登出成功')


#  新增用户
@bp_user.route('', methods=['POST'])
def addUser():
    account = request.json
    msg = AccountService.Account_Insert(Dict(account))
    return createForSuccessWM(msg)


#  通过id删除用户
@bp_user.route('<int:id>', methods=['DELETE'])
def deleteUser(id):
    msg = AccountService.Account_Delete(id)
    return createForSuccessWM(msg)


#   修改用户
@bp_user.route('', methods=['PUT'])
def updateUser():
    account = request.json
    commonResponse = AccountService.Account_Update(Dict(account))
    return commonResponse


#  通过id查找用户
@bp_user.route('<int:id>', methods=['GET'])
def selectUserById(id):
    account = AccountService.Account_Query_ByReaderID(id)
    if account is None:
        return createForErrorWM('通过id没找到此user')
    return createForSuccessWMD('查找成功', dict(account))


#  通过name查找用户
@bp_user.route('/name/<string:name>', methods=['GET'])
def selectUserByName(name):
    account = AccountService.Account_Query_ByUsername(name)
    if account is None:
        return createForErrorWM('通过name没找到此user')
    return createForSuccessWMD('查找成功', dict(account))


#  查找所有用户
@bp_user.route('', methods=['GET'])
def selectAllUser():
    accountList = AccountService.Account_Query_All()
    accountList1 = []
    for account in accountList:
        accountList1.append(dict(account))
    # print(accountList1)
    if not accountList1:
        return createForSuccessWM("没有任何用户")
    return createForSuccessWMD('查找成功', accountList1)


#  查找所有管理员
@bp_user.route('/admins', methods=['GET'])
def selectAllAdmin():
    accountList = AccountService.Account_Query_All1()
    accountList1 = []
    for account in accountList:
        accountList1.append(dict(account))
    if not accountList1:
        return createForSuccessWM("没有任何管理员")
    return createForSuccessWMD('查找成功', accountList1)


# 缴费功能
@bp_user.route('/<int:ReaderID>/<float:money>', methods=['PUT'])
def giveMoney(ReaderID, money):
    msg = LendService.Debt_Clear(ReaderID, money)
    return createForSuccessWM(msg)
